using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Xml;

public class InteractionSystem : MonoBehaviour 
{	
	private int dialogueCount = 0;
	
	public AudioSource[] audioSources;
	public AudioClip[] audioClips;	
	public XmlDocument doc;
	public XmlNode dialogue;
	public XmlNodeList reactions;
	public String[] player;
	public String[] npc;
	public GUIStyle myStyle;
	
	void Start () {
		
		// --- XML ---
		
		myStyle.wordWrap = true;
		myStyle.fontSize = 32;

		doc = new XmlDocument();
		
		var XmlData = (Resources.Load ("XML/Plot")).ToString();
		doc.LoadXml(XmlData);
		
		Debug.Log(XmlData);
		
		dialogue = doc.SelectSingleNode("Dialogue");
		reactions = dialogue.ChildNodes;
		
		player = new String[reactions.Count];
		npc = new String[reactions.Count];
		
	    for (int i=0; i < reactions.Count; i++)
	    {
	        player[i] = reactions[i].SelectSingleNode("Player").InnerText;
			npc[i] = reactions[i].SelectSingleNode("NPC").InnerText;
			Debug.Log("Spieler 1 sagt:" + player[i] + " NPC sagt: " + npc[i]);
	    }
		
		// --- Sound ---
		
		var info = new DirectoryInfo("Assets\\Resources\\Sounds");
		FileInfo[] fis = info.GetFiles();
		
		audioSources = new AudioSource[fis.Length];
		
		for (int s = 0; s < fis.Length; s++) {
		
			audioSources[s] = (AudioSource)gameObject.AddComponent("AudioSource");
			audioSources[s].playOnAwake = false;
			
			var path = Path.GetFileNameWithoutExtension(fis[s].ToString());
			
			AudioClip myAudioClip;
			myAudioClip = (AudioClip)Resources.Load("Sounds/" + path);
			
			audioSources[s].clip = myAudioClip;
			
			Debug.Log (fis[s] + " eingelesen!");
			
		}
		
	}
	
	void Update () {}

    void OnGUI()
    {
		try
		{	
			GUI.Label (new Rect (20, Screen.height - 100, Screen.width - 40, 60), player[dialogueCount], myStyle);
			if (GUI.Button(new Rect (20, 150, 100, 20), "Play") && dialogueCount < npc.Length)
			{
				PlaySound(audioSources[dialogueCount]);
				dialogueCount++;
			}
			
			if (IsTalking())
			{
				GUI.Label (new Rect (20, 20, Screen.width - 40, 60), npc[dialogueCount], myStyle);
			}
		}	
		catch(Exception ex)
		{
		    Console.WriteLine("Der Dialog wurde gestoppt (" + ex.Message + ")");
		}
	}
	
	private bool PlaySound (AudioSource sound) {
		sound.Play();
		return true;
	}
	
	public bool IsTalking(){
		if(audioSources[dialogueCount-1].isPlaying)
		{
		    return true;
		}
		else
		{
			return false;
		}

	}
	
}